/**
*  Copyright 2009-2015 by WWW.KNET.CN  All rights reserved.
*/
package cn.knet.sp.ncrm.modules.call.record.web;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.knet.sp.ncrm.common.aspect.ExportExcelLock;
import cn.knet.sp.ncrm.common.persistence.AjaxMessage;
import cn.knet.sp.ncrm.common.persistence.Page;
import cn.knet.sp.ncrm.common.service.ExportSynService;
import cn.knet.sp.ncrm.common.utils.DateUtils;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.common.web.BaseController;
import cn.knet.sp.ncrm.modules.call.record.entity.RecordInfo;
import cn.knet.sp.ncrm.modules.call.record.entity.RecordInfoQuery;
import cn.knet.sp.ncrm.modules.call.record.service.RecordInfoService;
import cn.knet.sp.ncrm.modules.sys.utils.ExcelUtils;

/**
 * TODO(这里用一句话描述这个类的作用)
 * @author Gehaiyang
 * @date 2015年6月29日 下午3:58:23
 * 
 */
@Controller
@RequestMapping(value="${adminPath}/call/record/recordinfo")
public class RecordInfoController extends BaseController{
	@Autowired
	private ExportSynService exportSynService;
	@Resource
	private RecordInfoService recordInfoService;
	@Value("${call.record.default.path}")
	private String record_path;
	
	@RequiresPermissions("call:record:view")
	@RequestMapping(value = {"/list", ""}, method = {RequestMethod.GET,RequestMethod.POST})
	public String list(Model model,RecordInfoQuery recordInfoQuery,HttpServletRequest request, HttpServletResponse response){
		Page<RecordInfo> page= new Page<RecordInfo>(request, response);
		page.setPageSize(100);
		Page<RecordInfo> pageData = recordInfoService.findPage(page, recordInfoQuery); 
		model.addAttribute("page", pageData);
		return "modules/call/record/recordInfoList";
	}
	
	@RequestMapping(value = "/download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		// 获得请求文件名
		String filePath = request.getParameter("filePath");
		// 设置文件MIME类型
		String contentType = filePath.substring(filePath.lastIndexOf(".")+1);
		response.setContentType(contentType);
		String oldName = filePath.substring(filePath.lastIndexOf("/")+1);
		String fileName = oldName.substring(0,oldName.indexOf("C",1)+15).replaceAll("[a-zA-Z]", "-") + "." + contentType;
		// 设置Content-Disposition
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		try {
			// 读取目标文件，通过response将目标文件写到客户端
			URL url = new URL(filePath);
			InputStream in = url.openConnection().getInputStream();
			OutputStream out = response.getOutputStream();
			// 写文件
			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
			out.close();
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}
	
	/**
	 *  TODO(批量下载录音)
	 * @author Gehaiyang
	 * @date 2015年7月2日 下午3:33:18
	 * @param fileNames
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/zipDownload")
	public void zipDownLoad(String[] fileNames,HttpServletRequest request, HttpServletResponse response){
		if(fileNames != null && fileNames.length > 0 ) {
			try {
				ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
				byte[] buffer = new byte[8192];
				int len = 0;
				for (int i = 0; i < fileNames.length; i++) {
					response.setContentType("zip");
					response.setHeader("Content-Disposition", "attachment;filename="+ DateUtils.getDate() + ".zip");
					String filePath = record_path + fileNames[i];
					URL url = new URL(filePath);
					String contentType = filePath.substring(filePath.lastIndexOf(".")+1);
					String oldName = filePath.substring(filePath.lastIndexOf("/")+1);
					String fileName = oldName.substring(0,oldName.indexOf("C",1)+15).replaceAll("[a-zA-Z]", "-") + "." + contentType;
					ZipEntry ze = new ZipEntry(fileName);
					zos.putNextEntry(ze);
					InputStream inputStream = url.openConnection().getInputStream();
					BufferedInputStream bis = new BufferedInputStream(inputStream);
					while ((len = bis.read(buffer))!= -1) {
						zos.write(buffer, 0, len);
					}
					bis.close();
					zos.closeEntry();
				}
				zos.close();
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
			}
		}
	}
	@RequestMapping(value = "/vaildateExport")
	@ResponseBody
	public Object vaildateExport(Model model,RecordInfoQuery recordInfoQuery,HttpServletRequest request, HttpServletResponse response){
		AjaxMessage result = AjaxMessage.success();
		try {
			if(StringUtils.isBlank(recordInfoQuery.getBeginDateTime())&&
					StringUtils.isBlank(recordInfoQuery.getEndDateTime())){
				result.makeError("导出时必须选择开始时间和结束时间!");
				return result;
			}
			java.util.Date begin = DateUtils.parseDate(recordInfoQuery.getBeginDateTime(), "yyyy-MM-dd HH:mm:ss");
			java.util.Date end = DateUtils.parseDate(recordInfoQuery.getEndDateTime(), "yyyy-MM-dd HH:mm:ss");
			double days = DateUtils.getDistanceOfTwoDate(begin, end);
			if(days>92){//超过半年 这个具体算法有待考证
				result.makeError("您的查询时间过长,一般不要超过3个月!");
				return result;
			}else{
				Page<RecordInfo> page= new Page<RecordInfo>(request, response);
				page.setPageSize(1); //仅查询一个 相当于count
				Page<RecordInfo> pageData = recordInfoService.findPage(page, recordInfoQuery);
				result.put("count",pageData.getCount());
			}

		} catch (ParseException e) {
			//e.printStackTrace();
			logger.warn("查询日期转换失败!",e);
			result.makeError("查询日期发生异常,请检查开始时间和结束时间是否正确");
		}
		return result;
	}

	@ExportExcelLock(lockerId = "callRecordsExport")
	@RequiresPermissions("call:record:view")
	@RequestMapping(value = "/mapExport", method = {RequestMethod.GET})
	public String mapExport(Model model,RecordInfoQuery recordInfoQuery,HttpServletRequest request, HttpServletResponse response){
		HashMap<String, Object> result = new HashMap<String, Object>();
		Page<RecordInfo> page= new Page<RecordInfo>(request, response);
		page.setPageSize(10000);
		Page<RecordInfo> pageData = recordInfoService.findPage(page, recordInfoQuery);
		List<RecordInfo> list = new ArrayList<RecordInfo>();
		while(hasNext(pageData)){
			result.put("hasNext",hasNext(pageData));
			result.put("next",pageData.getPageNo()+1);
			result.put("max",pageData.getLast());
			exportSynService.putValue("callRecordsExport",result);
			list.addAll(pageData.getList());
			/*for(RecordInfo vo:pageData.getList()){
				list.add(vo);
			}*/
			page.setPageNo(pageData.getPageNo()+1);
			pageData = recordInfoService.findPage(page, recordInfoQuery);
		}

		result.put("hasNext",hasNext(pageData));
		result.put("next", pageData.getPageNo() + 1);
		result.put("max", pageData.getLast());
		exportSynService.putValue("callRecordsExport",result);
		list.addAll(pageData.getList());

		ExcelUtils.Sheet sheet = new ExcelUtils.Sheet();
		sheet.setName("呼叫记录");
		sheet.setList(list);
		sheet.setRows(true);
		sheet.addColumn("工号", "agentID")
				.addColumn("姓名", "agentName")
				.addColumn("呼叫类型", "callTypeText")
				.addColumn("主叫号码", "dialingNO")
				.addColumn("被叫号码", "calledNO")
				.addColumn("呼叫开始时间", "beginTime","date","yyyy-MM-dd HH:mm:ss")
				.addColumn("呼叫结束时间", "endTime","date","yyyy-MM-dd HH:mm:ss")
				.addColumn("通话时长", "callTime")
				.addColumn("振铃时长", "ringTime")
				.addColumn("总时长", "totalTime");
		return exportSynService.exportSyn(sheet, model);
	}

	private boolean hasNext(Page<RecordInfo> page) {
		if(page.getPageNo()<page.getLast()){
			return true;
		}else{
			return false;
		}
	}
}
